/**
 * 
 */
package com.wgo.precise.client.ui.view.delegates;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;


import com.wgo.precise.client.common.session.PreciseSession;
import com.wgo.precise.client.common.session.PreciseSession.ObjectHolder;
import com.wgo.precise.client.ui.controller.ClientSession;
import com.wgo.precise.client.ui.controller.ModelStatus;
import com.wgo.precise.client.ui.controller.RequirementPlugin;
import com.wgo.precise.client.ui.controller.SessionHolderListener;
import com.wgo.precise.client.ui.view.util.ReflectionHelper;
import com.wgo.precise.client.ui.view.util.ReflectionRunnableWithProgress;

/**
 * @author Petter L. H. Eide 
 */
public class ExportXmlActionDelegate extends Action implements IWorkbenchWindowActionDelegate, SessionHolderListener {
	
	private FileDialog fileDialog;
	private IWorkbenchWindow window;
	
	public ExportXmlActionDelegate() {
		setEnabled(false);
	}
	/**
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
	 */
	public void dispose() {
		window = null;
		RequirementPlugin.getInstance().removeSessionHolderListener(this);
	}
	
	/**
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
	 */
	public void init(IWorkbenchWindow window) {
		this.window = window;
		RequirementPlugin.getInstance().addSessionHolderListener(this);
		setText("Import XML");
		fileDialog = new FileDialog(window.getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(new String[] { "*.xml" });
		fileDialog.setText("Select file to save Precise XML export.");
		fileDialog.setFileName("precise.xml");
		setToolTipText("Export Precise XML to to file.");
	}
	
	/**
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		if (!isEnabled()){ // this should never be true... but is... (disabeling an IWorkbenchWindowActionDelegate apearently does not work)
			MessageDialog.openInformation(window.getShell(), "Not logged in..", "You have to be logged in to be able to export data from server..");
			return;
		}
		ClientSession clientSession = RequirementPlugin.getInstance().getSession();
		PreciseSession session = clientSession.getDomainSession();
		if (session.isAnyDirty()) {
			MessageDialog dialog = new MessageDialog(RequirementPlugin.getInstance().getActiveShell(),
					"Save changes?", null, "You have unsaved changes, save?",
					MessageDialog.QUESTION, new String[] {
				IDialogConstants.OK_LABEL,
				IDialogConstants.NO_LABEL,
				IDialogConstants.CANCEL_LABEL }, 0);
			switch (dialog.open()) {
			case 0:
				clientSession.saveAll();
				break;
			case 1:
				break;
			case 2:
				return;
			}
		}
		
		String fileName = fileDialog.open();
		if (null == fileName) {
			return;
		}
		File file = new File(fileName);
		
		PreciseSession.ObjectHolder<byte[]> objectHolder = new PreciseSession().new ObjectHolder<byte[]>();
		IRunnableWithProgress op = new ReflectionRunnableWithProgress("Exporting data from " + session.getServerContextUrl() + " to " + file.getAbsolutePath(), ReflectionHelper.retrieveMethod(getClass().getSimpleName(), session.getClass(), "exportToXml", ObjectHolder.class), session, objectHolder);
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
			progressService.busyCursorWhile(op);
		} catch (InvocationTargetException e) {
			RequirementPlugin.logAndDisplay(new ModelStatus(IStatus.ERROR, "Error retriving XML-file from server.", e.getTargetException()));
		} catch (InterruptedException e) {
			RequirementPlugin.logAndDisplay(new ModelStatus(IStatus.ERROR, "Error retriving XML-file from server.", e));
		}
		FileOutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(file);
			outputStream.write(objectHolder.getObject());
			outputStream.flush();
		} catch (FileNotFoundException e) {
			RequirementPlugin.logAndDisplay(new ModelStatus(IStatus.ERROR,e.getMessage(), e));
			return;
		} catch (IOException e) {
			RequirementPlugin.logAndDisplay(new ModelStatus(IStatus.ERROR, "error writing to file", e));
			return;
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				RequirementPlugin.logAndDisplay(new ModelStatus(IStatus.ERROR, "error closing file", e));
			}
		}
	}
	
	/**
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {}
	
	public void setSessionSet(boolean ifSessionIsSet) {
		setEnabled(ifSessionIsSet);
	}

	
}
